package com.vay.de.dang.online.web;

import java.util.HashMap;
import java.util.Map;

import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.entiy.SignInEntity;
import com.vay.de.dang.online.entiy.PropertyRuleEntity;
import com.vay.de.dang.online.entiy.RegisterEntity;
import com.vay.de.dang.online.util.VnDefine;
import com.vay.de.dang.online.util.VnContext;

import org.json.JSONObject;

public class LoginApi extends BaseApi {

    public static void login(String phone, String code, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    // 1. check register
                    boolean uploadDevice = false;
                    //String url = wrapperUrl("loanSupermarket/notauth/validatePhoneRegistered/" + phone);
                    String url = wrapperUrl("bDnLET/JTd/BiwgvjYd/" + phone);
                    String json = doGet(url);
                    if (JsonUtil.isOk(json)) {
                        // 未注册
                        String msg = JsonUtil.readData(json);
                        if ("false".equals(msg)) {
                            //url = wrapperUrl("loanSupermarket/notauth/register");
                            url = wrapperUrl("COc/eHXLHJI/grUyfdd");
                            Map<String, Object> param = new HashMap<>();
                            param.put("channel", VnApp.getChannel());
                            param.put("password", "");
                            param.put("phone", phone);
                            param.put("verificationCode", code);
                            String str = JsonUtil.objectToJson(param);
                            json = doPostByJson(url, str);
                            if (JsonUtil.isOk(json)) {
                                RegisterEntity register = JsonUtil.toObjectByData(json, RegisterEntity.class);
                                uploadDevice = true;

                                // 注册事件
                                if (register != null) {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("appsFlyerId", VnDefine.APPFLYER_ID);
                                    map.put("userId", register.getUserId());
                                    VnApp.trackEventParam("registerSuccess", map);
                                }

                                // 业务埋点
                                execBuriedPoint(1561, 1500, "登录", "注册成功");

                            } else {
                                String error = JsonUtil.readMsg(json);

                                // 业务埋点
                                execBuriedPoint(1562, 1500, "登录", "注册失败", error);

                                return ReqResult.error(error);
                            }
                        }

                        // 登录
                        //url = wrapperUrl("loanSupermarket/notauth/verificationCodeLogon");
                        url = wrapperUrl("YcfLt/qLSQd/zIMyg");
                        Map<String, Object> param = new HashMap<>();
                        param.put("phone", phone);
                        param.put("verificationCode", code);
                        String str = JsonUtil.objectToJson(param);
                        json = doPostByJson(url, str);
                        if (JsonUtil.isOk(json)) {
                            SignInEntity entity = JsonUtil.toObjectByData(json, SignInEntity.class);
                            VnContext.instance().saveLogin(entity);

                            // 上传设备信息
                            if (uploadDevice) {
                                ReqResult error = DeviceApi.uploadPhoneInfo(1);
                                if (error != null && error.isOk()) {
                                    log("注册上传设备信息");
                                } else {
                                    log("警告: 注册上传设备信息");
                                }
                            }

                            // 登录事件
                            Map<String, Object> map = new HashMap<>();
                            map.put("appsFlyerId", VnDefine.APPFLYER_ID);
                            map.put("userId", entity.getUserId());
                            VnApp.trackEventParam("loginSuccess", map);

                            // 业务埋点
                            execBuriedPoint(1570, 1500, "登录", "登录成功");

                            return ReqResult.ok(entity);
                        } else {

                            // 业务埋点
                            String error = JsonUtil.readMsg(json);
                            execBuriedPoint(1580, 1500, "登录", "登录失败", error);
                        }
                    }

                    // 2. login
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    public static void mobileRule(ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    //String url = wrapperUrl("common/notauth/mobile");
                    String url = wrapperUrl("XNBlrsc/FdcNlXzh/qocKkJSk");
                    String json = doGet(url);
                    if (JsonUtil.isOk(json)) {
                        return ReqResult.ok(JsonUtil.toObjectByData(json, PropertyRuleEntity.class));
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReqResult.error(JsonUtil.readMsg(e.getMessage()));
                }
            }
        });
    }

    // 删除账号
    public static void deleteAccount(String phone, String code, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    Map<String, Object> map = new HashMap<>();
                    map.put("phone", phone);
                    map.put("verificationCode", code);
                    String param = JsonUtil.objectToJson(map);

                    String url = wrapperUrl("ZCiMmTg/IRFZ/kXeT");
                    String json = doPostByJson(url, param);
                    if (JsonUtil.isOk(json)) {
                        return ReqResult.ok(true);
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReqResult.error(JsonUtil.readMsg(e.getMessage()));
                }
            }
        });
    }

    // facebook 认证
    public static void callFacebook(String phone, String facebookId, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    //【phone->zKC,facebook->EBddVQ】
                    Map<String, String> map = new HashMap<>();
                    map.put("zKC", phone);
                    map.put("EBddVQ", facebookId);
                    //String url = wrapperUrl("/loanSupermarket/carrierOperator/vayhub/facebook/auth");
                    String url = wrapperUrl("/gTvbe/AGj/fdj/Crlx/AcRr");
                    String json = doPostByBody(url, null, map);
                    if (JsonUtil.isOk(json)) {
                        JSONObject jo = new JSONObject(json);
                        int code = jo.optInt("data");
                        return code == 1 ? ReqResult.ok(code) : ReqResult.error("Call facebook error");
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReqResult.error(JsonUtil.readMsg(e.getMessage()));
                }
            }
        });
    }

    // 第一次验证码
    public static void sendOneCode(String phone, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    // phone->kNcm
                    Map<String, String> map = new HashMap<>();
                    map.put("kNcm", phone);
                    //String url = wrapperUrl("loanSupermarket/carrierOperator/vayhub/first/validateCode");
                    String url = wrapperUrl("QQzmUv/AeltaiFB/hOlu/sxOaGqaj/ncFg");
                    String json = doPostByBody(url, null, map);
                    if (JsonUtil.isOk(json)) {
                        JSONObject jo = new JSONObject(json);
                        int code = jo.optInt("data");
                        return code == 1 ? ReqResult.ok(code) : ReqResult.error("Send first code error");
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReqResult.error(JsonUtil.readMsg(e.getMessage()));
                }
            }
        });
    }

    // 第二次验证码
    public static void sendSecondCode(String phone, String oneCode, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    // 【phone->vFmQ,firstValidateCode->dBtv】
                    Map<String, String> map = new HashMap<>();
                    map.put("vFmQ", phone);
                    map.put("dBtv", oneCode);
                    //String url = wrapperUrl("loanSupermarket/carrierOperator/vayhub/second/validateCode");
                    String url = wrapperUrl("GVNSgtU/MIzjrht/huxf/JyiKi/XAr");
                    String json = doPostByBody(url, null, map);
                    if (JsonUtil.isOk(json)) {
                        JSONObject jo = new JSONObject(json);
                        int code = jo.optInt("data");
                        return code == 1 ? ReqResult.ok(code) : ReqResult.error("Send second code error");
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReqResult.error(JsonUtil.readMsg(e.getMessage()));
                }
            }
        });
    }

    // Vietnamobile 验证
    public static void authByVietnamobile(String phone, String code, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    // 【phone->vqF,firstValidateCode->YoXfvic】
                    Map<String, String> map = new HashMap<>();
                    map.put("vqF", phone);
                    map.put("YoXfvic", code);
                    //String url = wrapperUrl("loanSupermarket/carrierOperator/vayhub/first/validateCode/sub");
                    String url = wrapperUrl("AWj/YUBxtpN/NjVmtSoz/WNimnK/ZnoQMTW/MAfOv");
                    String json = doPostByBody(url, null, map);
                    if (JsonUtil.isOk(json)) {
                        JSONObject jo = new JSONObject(json);
                        int code = jo.optInt("data");
                        // 提交验证结果
                        return authResultSub(phone, code);
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReqResult.error(JsonUtil.readMsg(e.getMessage()));
                }
            }
        });
    }

    // 其他方式验证
    public static void authByOther(String phone, String code, ReqCallback callback) {
        execTask(new WorkerBase(callback) {
            @Override
            public ReqResult doTask() {
                try {
                    // loanSupermarket/carrierOperator/vayhub/second/validateCode/sub——>/Piga/vlcwQ/pkje/kzNdso/UBB/OLcOO】
                    // 【phone->tKaCd,secondValidateCode->nhtLSh】
                    // 第二次验证码提交
                    Map<String, String> map = new HashMap<>();
                    map.put("tKaCd", phone);
                    map.put("nhtLSh", code);
                    //String url = wrapperUrl("loanSupermarket/carrierOperator/vayhub/second/validateCode/sub");
                    String url = wrapperUrl("Piga/vlcwQ/pkje/kzNdso/UBB/OLcOO");
                    String json = doPostByBody(url, null, map);
                    if (JsonUtil.isOk(json)) {
                        JSONObject jo = new JSONObject(json);
                        int code = jo.optInt("data");
                        // 提交验证结果
                        return authResultSub(phone, code);
                    } else {
                        return ReqResult.error(JsonUtil.readMsg(json));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReqResult.error(JsonUtil.readMsg(e.getMessage()));
                }
            }
        });
    }

    // 提交验证结果
    private static ReqResult authResultSub(String phone, int code) {
        try {
            //String url = wrapperUrl("loanSupermarket/carrierOperator/vayhub/auth/result/sub");
            // 【/loanSupermarket/carrierOperator/vayhub/auth/result/sub——>/kZGA/pkQbPup/faOmiILJ/lhkmV/khHsr/UaYQMgs】
            // 【phone->WNBWi,isAuth->WJSJ】
            String url = wrapperUrl("kZGA/pkQbPup/faOmiILJ/lhkmV/khHsr/UaYQMgs");
            Map<String, String> map = new HashMap<>();
            map.put("WNBWi", phone);
            map.put("WJSJ", code == 1 ? "true" : "false");
            String json = doPostByBody(url, null, map);
            if (JsonUtil.isOk(json)) {
                return ReqResult.ok("");
            } else {
                return ReqResult.error(JsonUtil.readMsg(json));
            }
        } catch (Exception e) {
            return ReqResult.error(JsonUtil.readMsg(e.getMessage()));
        }
    }
}
